const { ordersModel } = require('./models/ordersModel');
const { customersModel } = require('./models/customersModels');


// 获取销售员负责的所有订单
module.exports.getMyOrders = async ({ _id, currentPage, pageSize }) => {
    console.log(_id);
    // 订单集合 -> 关联客户id -> 关联销售员id

    // // 1. 通过销售员id查询客户id
    //  [ { _id: '123'} , { _id: '456'} ]  => [ '123', '456' ] '5fec664a22550000fb006a13'
    const usersId = (await customersModel.find({ salesman: _id }, '_id')).map(item => item._id);
    // // 2. 通过用户id查询订单
    const data = await ordersModel.find({ isDel: false, customersId: { $in: usersId } }).populate({
        path: 'insuresID',
    }).limit(pageSize - 0).skip(currentPage*pageSize);
    // 数据总条数
    const totals = await ordersModel.find({ isDel: false, customersId: { $in: usersId } }).populate({
        path: 'insuresID',
    })
    const total=totals.length
    const pageTotal = Math.floor(total / pageSize);
    return {data,total,pageTotal}
}

// 获取修改订单的信息
module.exports.getOrdersById = async params => {
    const data = await ordersModel.find(params).populate({
        path: 'insuresID',
    })
    console.log(data);
    return data;
}

// 修改订单
module.exports.updateOrder = async params => {
    return await ordersModel.updateOne({ _id: params._id }, params.update)
}

// 删除订单
module.exports.delOrder = async params => {
    const data = await ordersModel.updateOne(params, { isDel: true })
    return data;
}


// 退保申请
module.exports.cancelOrder = async params => {
    return await ordersModel.updateOne(params, { isWarranty: 1 })
}

//获取所有订单(管理员)
module.exports.getAllOrders = async ({currentPage,pageSize}) => {
    //获取总数据条数
    const total = (await ordersModel.find({ isDel: false }).populate({
        path: 'insuresID',
    })).length;

    const data = await ordersModel.find({ isDel: false }).populate({
        path: 'insuresID',
    }).limit(pageSize-0).skip(currentPage * pageSize);

    const pageTotal = Math.floor(total / pageSize);
    return {data,total,pageTotal};
}

// 客户下单
module.exports.addOrder = async params =>{
    return await ordersModel.create(params);
}

